package cn.edu.sgu.www.mhxysy.util;

import cn.edu.sgu.www.mhxysy.entity.system.User;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Objects;

/**
 * 获取用户信息的工具类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
public class UserUtils {

    /**
     * 得到Subject对象
     * @return Subject
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取登录的用户信息
     * @return User
     */
    public static User getLoginUser() {
        Subject subject = getSubject();

        if (subject.isAuthenticated()) {
            Object principal = subject.getPrincipal();

            if (principal instanceof User) {
                return (User) principal;
            }

            return null;
        }

        throw new GlobalException(ResponseCode.FORBIDDEN, "当前没有用户登录，获取用户信息失败...");
    }

    /**
     * 获取登录用户的ID
     * @return String
     */
    public static String getUserId() {
        User user = getLoginUser();

        return Objects.requireNonNull(user).getId();
    }

    /**
     * 获取登录的用户名
     * @return String
     */
    public static String getLoginUsername() {
        User user = getLoginUser();

        return Objects.requireNonNull(user).getUsername();
    }

}